package reflex;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author Yancy
 * @program springioctest
 * @create 2021-01-16
 */
public class TestReflex {
  public static void main(String[] args) throws Exception {
    //
    // 用forName获取class
    Class personClass = Class.forName("reflex.Person");
    System.out.println(personClass);
    // 成员方法
    Method[] methods = personClass.getMethods();
    //    for (Method m : methods){
    //        System.out.println(m);
    //    }
    Method method = personClass.getMethod("eat", String.class);
    Person p = new Person();
    method.invoke(p, "饭");

    System.out.println("==============");

    Class personClass2 = Person.class;
    System.out.println(personClass2);

    // 成员变量

    Field[] fields = personClass2.getFields();
    for (Field f : fields) {
      System.out.println(f);
    }

    Field pField = personClass2.getField("a");
    System.out.println(pField);
    Object o = pField.get(p);
    pField.set(p, 2);
    System.out.println(o);
    System.out.println(p);

    Person person = new Person();
    Class personClass3 = person.getClass();
    System.out.println(personClass3);
    // 构造方法
    Constructor constructor = personClass3.getConstructor(String.class, int.class);
    System.out.println(constructor);
    // 创建对象
    Object  person1 = constructor.newInstance("zhang", 22);
    System.out.println(person1);
  }
}
